package reit.ass3;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * The Class RentalRequests , container for all RentalRequst
 */
class RentalRequests {

	/** The rental requests. */
	private BlockingQueue<RentalRequest> fRentalRequests;

	/** The number of rental requests */
	private AtomicInteger size;


	/**
	 * Instantiates a new rental requests.
	 */
	public RentalRequests(){
		size = new AtomicInteger(0);
		this.fRentalRequests = new LinkedBlockingQueue<RentalRequest>();
	}

	/**
	 * Instantiates a new rental requests.
	 *
	 * @param data the data
	 */
	public RentalRequests(final List<RentalRequest> data){
		this();
		for (int i=0;i<data.size();i++){
			this.fRentalRequests.add(data.get(i));
			size.incrementAndGet();
		}
	}

	/** The rental request not found. */
	private Object fRentalRequestNotFound= new Object();

	/**
	 * Take.
	 *
	 * @return the rental request
	 */
	public RentalRequest take() {	
		
		
		RentalRequest rRentalRequest=null;
		try {
			rRentalRequest = this.fRentalRequests.take();
			size.decrementAndGet();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
		}
		return rRentalRequest;/*
		while (rRentalRequest==null){
			if (this.fRentalRequests.size()>0){
				try {
					rRentalRequest = this.fRentalRequests.take();
					size.decrementAndGet();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
				}
			}
			else if(this.fRentalRequests.size() == 0){ //there are no more rental requests to wait on
				return null;
			}
			if (rRentalRequest==null){
				synchronized (fRentalRequestNotFound) {
					try {
						fRentalRequestNotFound.wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						//e.printStackTrace();
					}
				}
			}
		}
		return rRentalRequest;*/
	}

	/**
	 * Adds the.
	 *
	 * @param tRentalRequest the RentalRequest
	 */
	public void add(final RentalRequest tRentalRequest){
		this.fRentalRequests.add(tRentalRequest);
		size.incrementAndGet();
		synchronized (fRentalRequestNotFound) {
			this.fRentalRequestNotFound.notifyAll();
		}

	}

	/**
	 * Adds the.
	 *
	 * @param tRentalRequests the list of rental requests
	 */
	public synchronized void add(final List<RentalRequest> tRentalRequests){
		for (int i=0;i<tRentalRequests.size();i++){
			this.fRentalRequests.add(tRentalRequests.get(i));
		}
	}


	/**
	 * Size.
	 *
	 * @return the int
	 */
	public int size(){
		return this.size.get();
	}
}
